<template>
  <div class="app-page">
    <el-table-form ref="form" :model="query">
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 170px; margin-right: 2px;">
          <el-option label="预约时间" value="appointmentDt" />
          <el-option label="下单时间" value="transactTime" />
          <el-option label="修改时间" value="updateTime" />
        </el-select>
        <el-date-picker
          v-show="dateType==='appointmentDt'"
          v-model="date1"
          type="date"
          :picker-options="pickerOptions"
          unlink-panels
          :clearable="false"
        />
        <el-date-picker
          v-show="dateType!=='appointmentDt'"
          v-model="date"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="orderCode" label="订单号" />
          <el-option value="contactPhone" label="客户电话" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="csmName" label="客户名称" />
          <el-option value="csmAddress" label="客户地址" />
        </el-select>
        <el-input v-model.trim="txt" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="修改来源:">
        <el-select v-model="query.updateFromPlatSource" multiple placeholder="请选择">
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in optionsMap.orderUpdateSource"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户类型:">
        <el-select
          v-model="query.csmTypeSource"
          multiple
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in optionsMap.customerTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="订单状态:">
        <el-select
          v-model="query.orderStatusSource"
          multiple
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option label="全部" :value="0" />
          <el-option
            v-for="item in optionsMap.orderStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属机构:">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
          @node-click="selectTreeChange"
          @select-clear="orgClear"
        />
      </el-form-item>

      <el-form-item class="merge-item">
        <el-select
          v-model="user_qtype"
          style="width: 170px; margin-right: 2px;"
          @change="qtypeChange"
        >
          <el-option value="ownerId" label="处理人" />
          <el-option value="transactId" label="下单人" />
        </el-select>
        <el-select
          v-model="user_qtype_value"
          :loading="$loadingPlugin.getOwnerList || $loadingPlugin.getTransactorList"
          filterable
          clearable
          placeholder="请选择"
        >
          <el-option
            v-for="item in userQtypeList"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否代亲友:">
        <el-select v-model="query.isRelatives" clearable>
          <el-option label="是" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="超时状态:">
        <el-select v-model="query.overTimeType" clearable>
          <el-option label="超时预警" :value="1" />
          <el-option label="已超时" :value="2" />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="[40107, 1]"
          :loading="$loadingPlugin.fetchData"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;" class="btn-group">
      <div>
        <el-button
          v-permission="[40107, 2]"
          :loading="$loadingPlugin.exportFile"
          type="primary"
          icon="el-icon-download"
          @click="exportFile"
        >导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      height="250"
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      :row-class-name="tableRowClassName"
      custom-column
      default-open
      @fetch="fetchData"
    />
    <csm-detail ref="csmDetail" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymentMethodMap" />
    <order-detail
      ref="orderDetail"
      :payment-method-map="paymentMethodMap"
      :pay-status-map="payStatusMap"
      :transactor-list="transactorList"
      :order-flag-map="orderFlagMap"
      :order-source-map="orderSourceMap"
      :order-status-map="optionsMap.orderStatusMap"
    />
    <csm-location ref="csmLocation" />
    <pay-detail ref="payDetail" :payment-method-map="paymentMethodMap" />
  </div>
</template>

<script>
  import {
    queryOwnerList,
    queryTransactorList,
    queryExportDomain,
    batchUserOrder,
    updateAppointList,
    appointUpdateExport
  } from '@/api'
  import { formatColumnMap, parseTime } from '@/utils'
  import getTreeData from '@/utils/jsonTree'
  import moment from 'dayjs'
  import { orderStatusObj, payStatusObj } from '@/utils/map'
  import CsmDetail from '../../../components/CsmDetailModal/index.vue'
  import OrderDetail from './OrderDetails'
  import PayDetail from './PayDetail'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import CsmLocation from '../../../components/CsmLocation'

  export default {
    components: {
      CsmDetail,
      OrderDetail,
      PayDetail,
      CsmLocation
    },
    props: {
      optionsMap: {
        type: Object,
        default: () => {}
      }
    },
    data() {
      return {
        pickerOptions: {
          disabledDate(time) {
            return moment(time.getTime()).diff(moment(Date.now()), 'days') < 0
          }
        },
        actionColWidth: 80,
        treeData: [],
        currentOrg: null,
        ownerList: [],
        transactorList: [],
        qtype: 'contactPhone',
        txt: '',
        orderSourceMap: [],
        orderFlagMap: [],
        user_qtype: 'ownerId',
        user_qtype_value: '',
        userQtypeList: [], // 下单人或处理人列表
        dateType: 'updateTime',
        date: [moment().startOf('day'), moment().endOf('day')],
        date1: parseTime(Date.now(), '{y}-{m}-{d}'),
        customerTypeMap: [],
        payStatusMap: [],
        paymentMethodMap: [],
        reStatusMap: [],
        calcTypeList: [],
        searchParams: {},
        query: {
          orgSNNo: '', // 所属机构orgSNNo
          updateFromPlatSource: [0],
          orderFlagSource: [0],
          isRemedy: '',
          orderStatusSource: [1, 2, 4, 5],
          csmTypeSource: [0],
          payStatus: '',
          paymentMethodSource: [0],
          reStatus: '',
          overTimeType: '',
          isRelatives: ''
        },
        roleTypeList: [],
        userList: [],
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData']),
      column: function() {
        return [
          {
            type: 'index',
            fixed: 'left'
          },
          {
            prop: 'orderCode',
            label: '订单号',
            width: 110,
            fixed: 'left',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openOrderDetail(row)}>
              {row.orderCode}
            </el-link>
          )
          },
          {
            prop: 'updateCount',
            label: '修改次数'
          },
          {
            prop: 'updateUserName',
            label: '修改人'
          },
          {
            prop: 'updateTime',
            label: '修改时间',
            width: 180,
            render: (h, { row }) => <span>{ row.updateTime && parseTime(row.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          },
          {
            prop: 'updateFromPlat',
            label: '修改来源',
            render: (h, { row }) => (
            <span>
              {row.updateFromPlat &&
                formatColumnMap(this.optionsMap.orderUpdateSource, 'value', row.updateFromPlat, 'desc')}
            </span>
          )
          },
          {
            prop: 'intSpare6',
            label: '是否代亲友',
            width: 100,
            render: (h, { row }) => (
            <span>
              {(row.intSpare6 >> 23 & 1) === 1 ? '是' : '否'}
            </span>
            )
          },
          {
            prop: 'ownerName',
            label: '处理人',
            showOverflowTooltip: true
          },
          {
            prop: 'orderStatus',
            label: '订单状态',
            render: (h, { row }) => (
            <span style={orderStatusObj[row.orderStatus]}>
              {row.orderStatus &&
                formatColumnMap(this.optionsMap.orderStatusMap, 'value', row.orderStatus, 'desc')}
            </span>
          )
          },
          {
            prop: 'csmCode',
            label: '客户编号'
          },
          {
            prop: 'csmName',
            label: '客户名称',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openCsmDetail(row)}>
              {row.csmName}
            </el-link>
          )
          },
          {
            prop: 'csmType',
            label: '客户类型',
            render: (h, { row }) => (
            <span>
              {row.csmType &&
                formatColumnMap(this.optionsMap.customerTypeMap, 'value', row.csmType, 'desc')}
            </span>
          )
          },
          {
            prop: 'contactPhone',
            label: '客户电话',
            width: 130,
            render: (h, { row }) => {
              if (row.contactPhone) {
                return (
                <span>
                  <svg-icon icon-class='call' onClick={e => window.pbx.dial(row.contactPhone, e)} />{row.contactPhone}
                </span>
              )
              }
              return ''
            }
          },
          {
            prop: 'csmAddress',
            label: '联系地址',
            width: 220,
            render: (h, { row }) => {
              return (
              <span>
                <span class='point-span'>
                  {this.$btnPermission([40107, 3]) && row.lon && row.lat && (
                    <i
                      onClick={() => this.openLocation(row)}
                      class='linkColor el-icon-location'
                      style='cursor: pointer;'
                    />
                  )}
                  {!this.$btnPermission([40107, 3]) && (
                    <i class='el-icon-location' style='color:#126edc;cursor: pointer;' />
                  )}
                </span>
                <span>{row.csmAddress}</span>
              </span>
              )
            }
          },
          {
            prop: 'appointmentDt',
            label: '预约时间',
            minWidth: 200,
            renderHeader: (h, scope) => {
              return <span>{ scope.column.label } <i class='el-icon-top' style='font-weight: 700;margin-right: 10px;' onClick={() => this.sortColumn(2, 1)}></i><i class='el-icon-bottom' style='font-weight: 700;' onClick={() => this.sortColumn(2, 2)}></i></span>
            },
            render: (h, { row }) => {
              return (
                <div class={this.getClass(row)}>
                  {(row.appointmentDt && row.dateTimeSpare1) && <span>{parseTime(row.dateTimeSpare1, '{h}:{i}') === '23:59' ? parseTime(row.appointmentDt, '{y}-{m}-{d}') : parseTime(row.appointmentDt, '{y}-{m}-{d} {h}:{i}') + ' 至 ' + parseTime(row.dateTimeSpare1, '{h}:{i}')}</span>}
                </div>
              )
            }
          },
          {
            prop: 'orgName',
            label: '责任机构',
            width: 160
          },
          {
            prop: 'transactor',
            label: '下单人',
            showOverflowTooltip: true
          },
          {
            prop: 'goodsDesc',
            label: '商品描述',
            width: 150
          },

          {
            prop: 'decimalSpare4',
            label: '订单总额',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openPayDetail(row)}>
              {row.decimalSpare4 && row.decimalSpare4.toFixed(2)}
            </el-link>
          )
          },
          {
            prop: 'distance',
            label: '配送距离(km)',
            align: 'center',
            width: 110,
            render: (h, { row }) => (
            <span>{row.distance && (row.distance / 1000).toFixed(2)}</span>
          )
          },
          {
            prop: 'taccReceivable',
            label: '实收金额',
            align: 'right',
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openPayDetail(row)}>
              {row.taccReceivable && row.taccReceivable.toFixed(2)}
            </el-link>
          )
          },
          {
            prop: 'overTimeType',
            label: '超时状态',
            width: 100,
            render: (h, { row }) => (
            <span class={row.overTimeType === 1 ? 'yellow' : 'red'} onClick={() => this.showTimeoutDetails(row)}>
              {row.overTimeType === 1 ? '超时预警' : row.overTimeType === 2 ? '已超时' : ''}
            </span>
            )
          },
          // {
          //   prop: 'transactTime',
          //   label: '下单时间',
          //   width: 140,
          //   renderHeader: (h, scope) => {
          //     return <span>{ scope.column.label } <i class='el-icon-top' style='font-weight: 700;margin-right: 10px;' onClick={() => this.sortColumn(1, 1)}></i><i class='el-icon-bottom' style='font-weight: 700;' onClick={() => this.sortColumn(1, 2)}></i></span>
          //   },
          //   render: (h, { row }) => (
          //   <span>
          //     {row.transactTime && parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}')}
          //   </span>
          // )
          // },
          // {
          //   prop: 'signDt',
          //   label: '送达时间',
          //   width: 180,
          //   render: (h, { row }) => <span>{ row.signDt && parseTime(row.signDt, '{y}-{m}-{d} {h}:{i}:{s}') }</span>
          // },
          {
            prop: 'intSpare4',
            label: '超时时间',
            width: 140,
            render: (h, { row }) => {
              if (row.intSpare4) {
                let h = Math.floor(row.intSpare4 / 60)
                let m = row.intSpare4 % 60
                // var s=v-60*h-60*m;
                if (h < 10) h = '0' + h
                if (m < 10) m = '0' + m
                return <span>{ h + ':' + m }</span>
              }
              return <span></span>
            }
          },
          // {
          //   prop: 'remark',
          //   label: '备注',
          //   width: 110
          // },

          // {
          //   prop: 'driverName',
          //   label: '大车司机',
          //   showOverflowTooltip: true
          // },
          // {
          //   prop: 'escortName',
          //   label: '押运员',
          //   showOverflowTooltip: true
          // },

          // {
          //   prop: 'goodsCount',
          //   label: '商品总数',
          //   align: 'right'
          // },

          // {
          //   prop: 'decimalSpare1',
          //   label: '总远距配送费',
          //   align: 'right',
          //   width: 110,
          //   render: (h, { row }) => (
          //   <span>{row.decimalSpare1 && row.decimalSpare1.toFixed(2)}</span>
          // )
          // },

          // {
          //   prop: 'decimalSpare2',
          //   label: '总上楼费',
          //   align: 'right',
          //   render: (h, { row }) => (
          //   <span>{row.decimalSpare2 && row.decimalSpare2.toFixed(2)}</span>
          // )
          // },
          // {
          //   prop: 'decimalSpare3',
          //   label: '总服务费',
          //   align: 'right',
          //   render: (h, { row }) => (
          //   <span>{row.decimalSpare3 && row.decimalSpare3.toFixed(2)}</span>
          // )
          // },
          // {
          //   prop: 'totalFee4',
          //   label: '优惠金额',
          //   align: 'right',
          //   render: (h, { row }) => (
          //   <el-link underline={false} onClick={() => this.openSpeciesAmount(row)}>
          //     {row.totalFee4 && row.totalFee4.toFixed(2)}
          //   </el-link>
          // )
          // },
          // {
          //   prop: 'treceivables',
          //   label: '应收金额',
          //   align: 'right',
          //   render: (h, { row }) => (
          //   <el-link underline={false} onClick={() => this.openPayDetail(row)}>
          //     {row.treceivables && row.treceivables.toFixed(2)}
          //   </el-link>
          // )
          // },

          {
            prop: 'payStatus',
            label: '支付状态',
            render: (h, { row }) => (
            <span style={payStatusObj[row.payStatus]}>
              {row.payStatus
                ? formatColumnMap(this.optionsMap.payStatusMap, 'value', row.payStatus, 'desc')
                : '未支付'}
            </span>
          )
          },
          {
            prop: 'paymentMethod',
            label: '支付方式',
            render: (h, { row }) => (
            <span>
              {row.paymentMethod &&
                formatColumnMap(
                  this.optionsMap.paymentMethodMap,
                  'value',
                  row.paymentMethod,
                  'desc'
                )}
            </span>
          )
          }

        ]
      }
    },
    watch: {
      'query.updateFromPlatSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.updateFromPlatSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.updateFromPlatSource.splice(val.indexOf(0), 1)
        }
        if (this.query.updateFromPlatSource.length === this.orderUpdateSource.length) {
          this.query.updateFromPlatSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.orderFlagSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderFlagSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderFlagSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderFlagSource.length === this.orderFlagMap.length) {
          this.query.orderFlagSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.orderStatusSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.orderStatusSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.orderStatusSource.splice(val.indexOf(0), 1)
        }
        if (this.query.orderStatusSource.length === this.optionsMap.orderStatusMap.length) {
          this.query.orderStatusSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.csmTypeSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.csmTypeSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.csmTypeSource.splice(val.indexOf(0), 1)
        }
        if (this.query.csmTypeSource.length === this.customerTypeMap.length) {
          this.query.csmTypeSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      },
      'query.paymentMethodSource': function(val, oldval) {
        const newindex = val.indexOf(0)
        const oldindex = oldval.indexOf(0) // 获取val和oldval里'全部'的索引,如果没有则返回-1
        if (newindex !== -1 && oldindex === -1 && val.length > 1) {
          // 如果新的选择里有勾选了'全部' 则 只勾选'全部'选项
          this.query.paymentMethodSource = [0]
        } else if (newindex !== -1 && oldindex !== -1 && val.length > 1) {
          // 如果操作前有勾选了'全部'且当前也选中了'全部'有且勾选数量大于1  则移除掉勾选'全部'
          this.query.paymentMethodSource.splice(val.indexOf(0), 1)
        }
        if (this.query.paymentMethodSource.length === this.paymentMethodMap.length) {
          this.query.paymentMethodSource = [0]
        } // 如果不勾选除'全部'外的其他项，则变为勾选'全部'
      }
    },
    async created() {
      await Promise.all([
        this.getExportDomain(),
        this.getTreeData(),
        this.getTransactorList()
      ])
      this.qtypeChange('ownerId')
    },
    methods: {
      getClass(r) {
        if (r.overTimeType) {
          if (r.overTimeType === 1) {
            return 'yellow'
          }
          if (r.overTimeType === 2) {
            return 'red'
          }
        }
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
        console.log(this.optionsMap, '-------------')
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async getUserOrder() {
        const params = {
          orgSNNo: this.query.orgSNNo
        }
        const res = await batchUserOrder(params)
        this.userList = res.data
      },
      sortColumn(sortColumn, sortType) {
        this.query.sortColumn = sortColumn
        this.query.sortType = sortType
        this.search()
      },
      csmTypeChange(csmType) {},
      async fetchData({ currentPage, pageSize }) {
        const query = {
          params: { ...this._getQuery(this.query) },
          currentPage,
          pageSize
        }
        query.params[this.qtype] = this.txt
        if (this.query.updateFromPlatSource[0] === 0) query.params.updateFromPlatSource = []
        query.params[this.user_qtype] = this.user_qtype_value
        if (this.query.orderFlagSource[0] === 0) query.params.orderFlagSource = []
        if (this.query.orderStatusSource[0] === 0) query.params.orderStatusSource = []
        if (this.query.csmTypeSource[0] === 0) query.params.csmTypeSource = []
        if (this.query.paymentMethodSource[0] === 0) query.params.paymentMethodSource = []
        if (this.date && this.date.length === 2) {
          if (this.dateType !== 'appointmentDt') {
            query.params[this.dateType] = moment(this.date[0]).format('YYYY-MM-DD HH:mm:ss')
            query.params[`${this.dateType}End`] = moment(this.date[1]).format('YYYY-MM-DD HH:mm:ss')
          }
          const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
          if (diff > 93) {
            this.$message.error('选择时间条件相差不能超过3个月')
            return
          }
        }
        if (this.dateType === 'appointmentDt' && this.date1) {
          query.appointmentDt = moment(this.date1).format('YYYY-MM-DD') + ' 00:00:00'
          query.dateTimeSpare1 = moment(this.date1).format('YYYY-MM-DD') + ' 23:59:59'
        }
        const res = await updateAppointList(query)
        this.searchParams = query.params
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 选择所属机构
      selectTreeChange(value) {
        this.currentOrg = value
        this.user_qtype_value = ''
        this.getOwnerList()
        // this.getUserOrder()
      },
      orgClear() {
        this.userList = []
        this.user_qtype_value = ''
      },
      // 配送距离数据格式化
      distanceFormat(v, r, i) {
        if (!Number(v)) {
          return ''
        }
        var msg = (Number(v) / 1000 || 0).toFixed(2)
        return msg
      },
      // 获取处理人列表
      async getOwnerList() {
        const b = (this.corpSettingData.sp1 >> 2) & 0x01
        const orgId = this.currentOrg ? this.currentOrg.orgId : -1
        const res = await queryOwnerList({
          orgId,
          corpparm1: b
        })
        this.ownerList = res.data
        this.userList = res.data
        if (this.user_qtype === 'ownerId') this.userQtypeList = this.ownerList
        else this.userQtypeList = this.transactorList
      },
      // 获取下单人列表
      async getTransactorList() {
        const res = await queryTransactorList({})
        this.transactorList = res.data
      },
      // 处理人或下单人选择
      qtypeChange(value) {
        if (value === 'ownerId') this.userQtypeList = this.ownerList
        else this.userQtypeList = this.transactorList
      },

      // 点击地址
      async openLocation(row) {
        await this.$refs.csmLocation.open(row)
      },
      // 点击客户名称
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row)
      },
      // 点击订单号
      async openOrderDetail(row) {
        await this.$refs.orderDetail.open(row, true)
      },
      // 点击订单总额
      async openPayDetail(row) {
        await this.$refs.payDetail.open(row)
      },

      async scoresMerge() {
        await this.$refs.scoresMerge.open()
      },
      async infoCircul() {
        // 参数为订单号
        await this.$refs.infoCircul.open('176697')
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain).then((res) => {
          this.exportDomain = res.data
        })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          const str = {}
          copyColumn.forEach((item) => {
            if (item.prop === 'intSpare6') {
              str['isRelatives'] = item.label
            } else {
              str[item.prop] = item.label
            }
          })
          const params = this.searchParams
          params.tabType = 6
          appointUpdateExport({
            paramInfo: _this._getQuery(params),
            kv: str // 表格列
          }).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 设置行类名
      tableRowClassName({ row }) {
        // if (row.orderStatus === 7 || row.orderStatus === 3) {
        //   // 7:已退单 3:退单申请中
        //   return 'danger-row'
        // }
        // if (row.orderStatus === 9 || row.orderStatus === 12) {
        //   // 9:退货申请中 12:已退货
        //   return 'giveup-row'
        // }
        // return ''
      },
      async showTimeoutDetails(row) {
        this.$refs.orderDetail.open(row, 'overTime')
      }
    }
  }
</script>

<style lang="scss" scoped>
.el-form-item .el-form-item {
  margin-bottom: 0;
}
.merge-item {
  /deep/ .el-form-item__content {
    display: flex;
  }
}
.btn-group {
  display: flex;
  justify-content: space-between;
}
/deep/ .el-table tr.danger-row {
  background: #ffeced;
}
/deep/ .el-table tr.giveup-row {
  background: #ffeced;
}
/deep/.red {
  color: #f00 !important;
  cursor: pointer;
}
/deep/.yellow {
  color: #ed912e !important;
  cursor: pointer;
}
</style>
